var express = require('express')
var path = require('path')
var bodyParser = require('body-parser')
var session = require('express-session')

// 导入路由模块
var index = require('./routes/index')
var register = require('./routes/register')
var login = require('./routes/login')
var get_topic_content = require('./routes/get_topic_content')
var issue_topic = require('./routes/issue_topic')
var get_topic_comment = require('./routes/get_topic_comment')
var get_topic_author = require('./routes/get_topic_author')
var issue_comment = require('./routes/issue_comment')
var uploads = require('./routes/uploads')
var user_info = require('./routes/user_info')
var agree_favorite = require('./routes/agree_favorite')
var search = require('./routes/search')
var change_topic = require('./routes/change_topic')
var attention_user = require('./routes/attention_user')

var app = express()

//开放路径
app.use('/public/', express.static(path.join(__dirname, './public/')))
app.use('/node_modules/', express.static(path.join(__dirname, './node_modules/')))


// 配置解析表单 POST 请求体插件（注意：一定要在 app.use(router) 之前 ）
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

// 设置跨域和相应数据格式
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:8080')
  res.header('Access-Control-Allow-Credentials', 'true')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
  res.setHeader('Content-Type', 'application/json;charset=utf-8')
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('X-Powered-By', ' 3.2.1')
  next()
})

//配置session对象
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}))

//挂载router
app.use(index)
app.use(register)
app.use(login)
app.use(get_topic_content)
app.use(issue_topic)
app.use(get_topic_comment)
app.use(get_topic_author)
app.use(issue_comment)
app.use(uploads)
app.use(user_info)
app.use(agree_favorite)
app.use(search)
app.use(change_topic)
app.use(attention_user)

app.listen(3000, function () {
  console.log('3000 is running......');
})